

--local t = math.random()  -- [0,1)
--local t = math.random(3) --[1,3]
--local t = math.random(2,4) --[2,4]
--math.randomseed(os.time())
--返回字符串s反序字符串 string:reverse()
-- local seed = tostring(os.time()):reverse():sub(1, 7) --5419877
-- math.randomseed(tostring(os.time()):reverse():sub(1, 7))
-- local t = math.random(2,4)
-- print(seed)
-- print(t)


--jump consistent hash 通过一种非常简单的跳跃算法对给
--定的对象 key 算出该对象被映射的服务节点

--key 请求key
--num_buckets 桶的数量
--return 索引位置
JumpConsistentHash = function(key, num_buckets)
    assert(key > 0)
    assert(num_buckets > 0)
    math.randomseed(key)

    local b = -1 --previous jump flag
    local j = 0 --current jump flag

    while(j < num_buckets) do
        b = j;
        --随机不需要对所有节点都进行一次随机，而是通过随机值跳跃了部分节点的比较
        local r = math.random() -- r (0,1)
        j = math.floor((b + 1) / r)
    end
    return b
end


JumpConsistentHash2 = function(key, num_buckets)
    assert(key > 0)
    assert(num_buckets > 0)

    local b = -1 --previous jump flag
    local j = 0 --current jump flag
    while(j < num_buckets) do
        b = j;
        key = key * 2862933555777941757 + 1
        j = (b + 1) * ( (1 << 31) / ((key >> 33) + 1) )
    end
    return b
end


local index = JumpConsistentHash2(1,10)
print(string.format("index number is".." "..index))